package com.ykyl.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */
public class AliOSSUtils {

    private String endpoint = "oss-cn-beijing.aliyuncs.com";
    private String accessKeyId = "LTAI5t7c4vGWXrtpwSUPHxpr";
    private String accessKeySecret = "8bkT024QHuj3VIx15Dk7EjcnIKpl7j";
    private String bucketName = "yikangyanglao";

    /**
     * 实现上传本地文件到OSS
     */
    public String upload(File file) throws IOException {
        // 获取上传的文件的输入流
        FileInputStream inputStream = new FileInputStream(file);

        // 避免文件覆盖，生成唯一文件名
        String originalFilename = file.getName();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.putObject(bucketName, fileName, inputStream);
        } finally {
            inputStream.close(); // 确保流被关闭
            ossClient.shutdown(); // 关闭ossClient
        }

        // 文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        return url; // 返回上传到OSS的路径
    }
}